package com.ruoyi.common.utils.file;

import cn.hutool.core.util.XmlUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.json.XML;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author : zhenhc
 * @date : 2022-04-17 16:22
 **/
public class XmlUtils {

    /**
     * xml文件转为json对象
     * @param pathname 文件路径
     * @return json对象
     */
    public static JSONObject toJSONObject(String pathname){
        //读取xml路径为document
        Document document = XmlUtil.readXML(pathname);
        //document转为string字符串
        String s = XmlUtil.toStr(document);
        //string字符串转为json对象
        JSONObject jsonObject = XML.toJSONObject(s);
        return jsonObject;
    }
    /**
     * 得到所有节点
     * @param pathname 文件路径
     * @return
     */
    public static List<Map<String,String>> getAllNode(String pathname){
        Document document = XmlUtil.readXML(new File(pathname));
        //获取根节点
        Element documentElement = document.getDocumentElement();
        List<Map<String,String>> mapList = new ArrayList<>();
        //递归调用添加节点到list集合里
        addNodeMapToList(documentElement,mapList);
        return mapList;
    }
    public static void addNodeMapToList(Node node, List<Map<String,String>> mapList) {
        Map<String,String> map = new HashMap<>();
        String nodeName = node.getNodeName();
        String nodeValue = node.getFirstChild().getNodeValue();
        map.put(nodeName,nodeValue.trim());
        mapList.add(map);
        NodeList nodeList = node.getChildNodes();
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node currentNode = nodeList.item(i);
            if (currentNode.getNodeType() == Node.ELEMENT_NODE) {
                addNodeMapToList(currentNode,mapList);
            }
        }
    }
}
